﻿namespace WLFramework.Validation
{

    using System;

    [AttributeUsage(AttributeTargets.Property)]
    public class RangeAttribute : ValidationAttribute
    {
        public double MinNum { get; set; }
        public double MaxNum { get; set; }

        public RangeAttribute(double minNumber, double maxNumber) :
            this(minNumber, maxNumber, "字段\'{0}\'的取值范围必须在" + minNumber + "-" + maxNumber + "之间")
        {
        }

        public RangeAttribute(double minNumber, double maxNumber, string displayErrors)
            : this(minNumber, maxNumber, displayErrors, "请输入{0}")
        {
        }

        public RangeAttribute(double minNumber, double maxNumber, string displayErrors, string displayDefault)
        {
            this.MinNum = minNumber;
            this.MaxNum = maxNumber;
            this.ErrorMessage = displayErrors;
            this.DefaultMessage = displayDefault;
        }

        public override ValidatePriority Priority
        {
            get
            {
                return ValidatePriority.High;
            }
        }

        public override ValidateResult IsValid(object input, ValidateContext context)
        {
            try
            {
                double Num = Convert.ToDouble(input);
                if (Num >= this.MinNum && Num <= this.MaxNum)
                {
                    return ValidateResult.Success;
                }
            }
            catch
            {
            }

            return new ValidateResult(this.FormatErrorMessage(context.DisplayName));
        }
    }
}

